﻿// Copyright (c) Vitaly Kamiansky. All rights reserved. 
// See License.txt in the project root.

using System;

namespace Property.Workers
{
    public class RetryWorkerDecorator<T> : WorkerDecorator<T>
    {
        protected RetryWorkerDecorator(IWorkerPrototype<T> compositionBasePrototype, Func<T> getValue, int retryCount)
            : base(compositionBasePrototype, getValue)
        {
            if (retryCount < 1) throw new ArgumentOutOfRangeException("retryCount");

            _RetryCount = retryCount;
        }

        //=//

        private readonly int _RetryCount;
        private int TriesState;

        protected override void Finished(object sender, EventArgs e)
        {
            if (Exception == null || ++TriesState >= _RetryCount)
                OnFinished();
            else
                _CompositionBase.Go();
        }

        public override void Go()
        {
            TriesState = 0;
            _CompositionBase.Go();
        }
    }
}
